<template>
  <div class="cost-summary">
    <ProTable ref="merchant_reg_fre" :immediate="true" :pagination="true" :search-form="formList" :columns="columns"
      :request="queryMerchantRegPage" :onRequestSuccess="requestSuccessCallback">
      <template #extra>

      </template>
    </ProTable>


    <!-- 编辑弹窗 -->
    <Modal v-model="merchantRegShow"  :title="merchantRegTitle">
      <Loading :loading="false">
        <Form ref="dataModule" :label-width="130" :model="merchantReg" :rules="merchantRegRuleValidate">
          <FormItem label="认证状态：" prop="applyStatus" >
            <RadioGroup v-model="merchantReg.applyStatus">
                <Radio label="1">通过</Radio>
                <Radio label="2">不通过</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="支付商户号：">
            <Input type="text" v-model="merchantReg.channelMerNo" placeholder="请填写支付商户号" clearable/>
          </FormItem>
          <FormItem label="企业号：">
            <Input type="text" v-model="merchantReg.companyNo" placeholder="请填写支付企业号" clearable/>
          </FormItem>
        </Form>
      </Loading>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="handleSubmitCancel('dataModule')">取消</Button>
        <Button type="primary" @click="handleSubmit('dataModule')">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import ProTable from '@/components/ProTable';
import { queryMerchantRegPage, manualSettingChannelInfo,allOrg } from '@/api/merchant';
import Loading from "@/components/Loading";
import util from '@/utils/util'
import Authc from "@/components/Authc";
import { resolveComponent } from 'vue';

export default {
  name: 'OrgBusiness',
  components: {
    ProTable,
    Authc,
    Loading
  },
  data() {
    return {
      title: '商户进件管理',
      isShow: false,
      exportSection: [],
      selectExportSectionItem: {},
      orgBusiness: {
        id: null,
        organizationCode: null,
        businessCode: null,
        orgPaymentChannelId: null,
        idPre: null,
        clientId: null,
        paymentChannelCode: null,
      },
      ruleValidate: {
        businessName: [{ required: true, message: '业务名称不能为空', trigger: 'blur' }]
      },
      merchantRegRuleValidate:{
        applyStatus: [{ required: true, message: '请选择认证状态', trigger: 'blur' }]
      },
      orgList:[],// 机构选择
      businessList:[],// 业务选择
      merchantRegShow:false,
      merchantRegTitle:'机构业务管理',
      merchantReg:{
        id:null,
        applyStatus:1,// 机构编码
        channelMerNo:'',// 支付商户号
        companyNo:'',// 企业号
      },
      formList: [
        {
          type: 'input',
          name: 'organizationCode',
          label: '机构编码',
        },
        {
          type: 'input',
          name: 'merchantCode',
          label: '商户编码',
        },
        {
          type: 'input',
          name: 'merchantName',
          label: '商户名称',
        },
        {
          type: 'select',
          name: 'applyStatus',
          label: '认证状态',
          option:[

          ]
        },
      ],
      columns: [
        {
          title: '机构名称',
          key: 'organizationName',
          align: 'center',
        },
        {
          title: '机构编码',
          key: 'organizationCode',
          align: 'center',
        },
        {
          title: '商户名称',
          key: 'merchantName',
          align: 'center',
        },
        {
          title: '商户编码',
          key: 'merchantCode',
          align: 'center',
        },
        {
          title: '商户类型',
          key: 'merchantType',
          align: 'center',
          render: (h, params) => {
            let text=""
            let color='blue'
            if(params.row.merchantType=='1'){
              text="企业"
            } else if(params.row.merchantType=='2'){
              text="个体"
              color='green'
            }else if(params.row.merchantType=='3'){
              text="小微"
              color='red'
            }
            return h('div', [
              h('Tag', {
                props: {
                  color:color
                },
              }, text),
            ])
          }

        },
        {
          title: '机构支付通道',
          key: 'orgPaymentChannelId',
          align: 'center',
        },
        {
          title: '支付渠道编码',
          key: 'paymentChannelCode',
          align: 'center',
        },
        {
          title: '注册时间',
          key: 'createdDt',
          align: 'center',
        },
        {
          title: '进件状态',
          key: 'applyStatus',
          align: 'center',
          render: (h, params) => {
            let text=""
            let color='blue'
            if(params.row.applyStatus==0){
              text="申请中"
            } else if(params.row.applyStatus==1){
              text="申请通过"
              color='green'
            }else if(params.row.applyStatus==2){
              text="失败"
              color='red'
            }
            return h('div', [
              h('Tag', {
                props: {
                  color:color
                },
              }, text),
            ])
          }
        },
        {
          title: '支付商户号',
          key: 'channelMerNo',
          align: 'center',
        },
        {
          title: '当前注册节点',
          key: 'regCurrentFlows',
          align: 'center',
        },
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            let buts=[]
            if((params.row.applyStatus==0 || params.row.applyStatus==2)){
              buts.push(h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.openMerchantRegModel(params.row)
                  }
                }
              }, '设置支付商户'))
            }
            buts.push(h('A', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.viewItem(params.row.id)
                  }
                }
              }, '详情'))
            return h('div', [...buts])
          }
        },
      ]
    };
  },
  created() {
    this.initOrgList()
  },
  methods: {
    queryMerchantRegPage,
    async initOrgList(){
      const res= await allOrg()
      if(res.status===200){
        const {data}=res
        if(data){
          console.log(data.data)
          let orgList=[]
          data.data.forEach((d)=>{
            orgList.push({
              label:d.organizationName,
              value:d.organizationCode
            })
          })
          this.orgList=orgList
          console.log("this.orgList:",orgList)
        }
      }
      console.log('initOrgList:',res)
    },
    async selectExportSection(item) {
      this.selectExportSectionItem = item
    },
    //查询成功回调
    async requestSuccessCallback(res) {
      if (res && res.data.pagination) {
        const total = res.data.pagination.total || 0
        if (total) {
          const sections = Math.ceil(total / 5000)
          let newExportSection = []
          for (let i = 1; i <= sections; i++) {
            newExportSection.push({
              id: i,
              start: (i - 1) * 5000 === 0 ? 1 : (i - 1) * 5000,
              end: i * 5000
            })
          }
          console.log(this.exportSection)
          this.exportSection = newExportSection
        } else {
          this.exportSection = []
        }
      } else {
        this.exportSection = []
      }
    },

    async openMerchantRegModel(params) {
      if (params && params.id) {
        this.addtype = "update"
      } else {
        this.addtype = "add"
      }
      this.merchantReg={
        id:params.id,
        applyStatus:params.applyStatus,// 机构编码
        channelMerNo:params.channelMerNo,// 支付商户号
        companyNo:params.companyNo,// 企业号
      }
      this.merchantRegShow = true
    },

    handleSubmitCancel(formName) {
      this.merchantRegShow = false
      this.merchantReg={
        id:null,
        applyStatus:1,// 机构编码
        channelMerNo:'',// 支付商户号
        companyNo:'',// 企业号
      }
      this.$refs[formName].resetFields()
    },
    async handleSubmit(name) {
      let that = this
      that.$refs[name].validate(async valid => {
        if (valid) {
          if(that.merchantReg.applyStatus==1){
            // 通过
            if(!that.merchantReg.channelMerNo){
              console.log('!that.merchantReg.channelMerNo...')
              that.$Notice.error({
                    title: '参数异常',
                    desc: '请填写支付商户号！'
                });
                return
            }
          }
          await manualSettingChannelInfo(that.merchantReg)
          that.$refs.merchant_reg_fre.onSearch();
          that.merchantRegShow = false;

        } else {
          console.log('error submit!!')
          // return false
        }
      })
    },
    // 重置
    resetForm() {
      if (this.$refs['dataModule'].fields) {
        this.$refs['dataModule'].fields.forEach(function (e) {
          if (e.prop == 'businessName') e.resetField();
        })
      }
    },

    bindleOrgChange(item){
      console.log('bindleOrgChange:',item)
    },
    viewItem(id){
      this.$router.push("/tenant/admin/tenantCenter/merchantRegDetail?id="+id);
    }
  }
};
</script>

<style>
.selectSectionItem {
  color: #2b85e4;
}
</style>
